import json
import re

from django.shortcuts import render
from django.views import View

# Create your views here.
from apps.area.models import Area
from django.http import JsonResponse
from django.core.cache import cache


class ProvinceAreasView(View):

    def get(self, request):

        province_list = cache.get('province_list')

        if not province_list:

            try:
                provinces = Area.objects.filter(parent__isnull=True)
                province_list = []

                for province in provinces:
                    province_list.append({
                        'id': province.id,
                        'name': province.name
                    })

                cache.set('province_list', province_list, 3600)
            except Exception as e:
                return JsonResponse({'code': 200, 'errmsg': '数据库读取失败'})

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'province_list': province_list})


class SubAreasView(View):

    def get(self, request, pk):

        subs_data = cache.get('subs_%s' % pk)

        if not subs_data:
            try:
                parent = Area.objects.get(id=pk)
                subs_data = {
                    'id': pk,
                    'name': parent.name,
                    'subs': []
                }

                sub_model_list = Area.objects.filter(parent=pk)

                for sub_model in sub_model_list:
                    subs_data['subs'].append({
                        'id': sub_model.id,
                        'name': sub_model.name
                    })

                cache.set('subs_%s' % pk, subs_data, 3600)
            except Exception as e:
                 return JsonResponse({'code': 200, 'errmsg': '数据库读取错误'})

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'sub_data': subs_data})












